from HTMLParser import HTMLParser


class HTMLStripper(HTMLParser):
    """
    Global parser for stripping HTML tags:
    The 'tag stripping' is implicit, because this parser echoes every
    type of html data *except* the tags.
    """
    def __init__(self):
        self._result = []
        self.safe_tags = set(['hr', 'br', 'img', 'div', 'span', 'b', 'pre',
                     'blockquote', 'i', 'p', 'a', 'table', 'tr', 'td', 'font',
                     'sup', 'sub', 'ul', 'li', 'ol', 'dd', 'dt', 'dl', 'h1',
                     'h2', 'h3', 'h4', 'h5', 'h6', 'em', 'strong'])

    def full_strip(self):
        self.safe_tags = []

    @property
    def result(self):
        return ''.join(self._result)

    def handle_data(self, data):
        """
        quote cdata literally
        """
        self._result.append(data)

    def handle_entityref(self, name):
        """
        entities must be preserved exactly
        """
        self._result.append('&')
        self._result.append(name)
        self._result.append(';')

    def handle_charref(self, name):
        """
        charrefs too
        """
        self._result.append("&#")
        self._result.append(name)
        self._result.append(";")

    def handle_starttag(self, tag, attrs):
        if tag in self.safe_tags:
            self._result.append('<')
            self._result.append(tag)
            for name, value in attrs:
                if name.lower().startswith('on') or value.lower().startswith('javascript'):
                    continue

                self._result.append(' ')
                self._result.append(name)
                self._result.append('="')
                self._result.append(value)
                self._result.append('"')
            self._result.append('>')

    def handle_startendtag(self, tag, attrs):
        if tag in self.safe_tags:
            self._result.append('<')
            self._result.append(tag)
            for name, value in attrs:
                if name.lower().startswith('on') or value.lower().startswith('javascript'):
                    continue

                self._result.append(' ')
                self._result.append(name)
                self._result.append('="')
                self._result.append(value)
                self._result.append('"')
            self._result.append(' />')

    def handle_endtag(self, tag):
        if tag in self.save_tags:
            self._result.append('</')
            self._result.append(tag)
            self._result.append('>')

def sanitize_name(name):
    stripper = HTMLStripper()
    stripper.full_strip()
    stripper.feed(name)
    stripper.close()

    return stripper.result

def sanitize_text(self, text):
    stripper = HTMLStripper()
    stripper.feed(name)
    stripper.close()

    return stripper.result